package com.bwie.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.mapper.GoodsMapper;
import com.bwie.pojo.Goods;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SyncEs implements ApplicationRunner {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    RestHighLevelClient client=new RestHighLevelClient(
            RestClient.builder(new HttpHost("47.102.97.160",9200,"http"))
    );


    private static final String INDEX_NAME="goods";

    @Override
    public void run(ApplicationArguments args) throws Exception {

        List<Goods> goodsList=goodsMapper.findAll();
        redisTemplate.opsForValue().set("goodsList",JSONObject.toJSONString(goodsList));
        try {
            for (Goods goods : goodsList) {
                IndexRequest indexRequest = new IndexRequest(INDEX_NAME);
                indexRequest.id(goods.getId()+"");
                indexRequest.source(JSONObject.toJSONString(goods), XContentType.JSON);
                client.index(indexRequest, RequestOptions.DEFAULT);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
